<template>
  <div
    v-if="!data.selectType"
    class="w-[100%] h-[100%] flex items-center justify-center text-[32px]"
  >
    请选择合同
  </div>
  <div v-else>
    <div class="mb-[20px] flex">
      <a-button type="primary" class="mr-[20px]" @click="addAddress">添加目的地</a-button>
      <ImageUpload
        v-model:value="fileList"
        :maxNumber="500"
        class="mr-[10px]"
        listType="text"
        :accept="['xls', 'xlsx', 'doc', 'docx']"
        :uploadParams="{
          freightTypeId: data.freightTypeId,
          freightType: data.freightType,
          contractId: data.contractId,
          carrierMid: data.mid2,
          ownerMid: data.mid,
        }"
        :api="uploadFreightTemplate"
        :showUploadList="false"
        @change="handleAttachmentChange"
        ><a-button type="primary" class="mr-2">上传运费数据</a-button></ImageUpload
      >
      <a-button type="primary" class="mr-[20px]" @click="download">下载导入模版</a-button>
    </div>
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction stopButtonPropagation :actions="createActions(record)" />
        </template>
      </template>
      <template #expandedRowRender="{ record }">
        <FreightDetailTable ref="FreightDetailRef" :detailInfo="{ ...record }" />
      </template>
    </BasicTable>
  </div>

  <DestinationForm @register="registerDestinationModal" :title="`新增目的地`" @on-search="reload" />
</template>
<script lang="ts" setup>
  import { message } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction, ActionItem, EditRecordRow } from '@/components/Table';
  import {
    getFreightInfoListAPI,
    deleteByCode,
    downloadFreightTemplate,
    uploadFreightTemplate,
  } from '@/api/eslogis-tps/index';
  import { downloadFile } from '@/utils/common/index';
  import DestinationForm from './DestinationForm.vue';
  import FreightDetailTable from './FreightDetailTable.vue';
  import ImageUpload from '@/components/Upload/src/components/ImageUpload.vue';
  import { useModal } from '@/components/Modal';
  import { ref } from 'vue';

  const FreightDetailRef = ref(null);

  const expendStatus = ref(false);

  // 获取外部传入的数据
  const { data } = defineProps({
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  console.log('🚀 ~ data:', data);

  const fileList = ref([]);

  const detailInfo = ref({
    freightType: data.freightType,
    freightTypeId: data.freightTypeId,
    contractId: data.contractId,
    carrierMid: data.mid2,
    ownerMid: data.mid,
    originCode: '',
    destCode: '',
  });

  const columns = [
    {
      title: '起运地城市',
      dataIndex: 'origin',
    },
    {
      title: '目的地城市',
      dataIndex: 'dest',
    },
    {
      ifShow: false,
      title: '起点编码',
      dataIndex: 'originCode',
    },
    {
      ifShow: false,
      title: '终点区编码',
      dataIndex: 'destCode',
    },
    {
      width: 160,
      title: '操作',
      dataIndex: 'action',
    },
  ];

  const id = ref(0);

  const [registerTable, { reload }] = useTable({
    accordion: true, // 手风琴效果
    columns: columns,
    showIndexColumn: false,
    immediate: false,
    expandRowByClick: true,
    canResize: false,
    scroll: { y: '100%' },
    pagination: true,
    showTableSetting: false,
    rowKey: 'id',
    showSelectionBar: false, // 显示多选状态栏
    onExpand: async (expanded, record) => {
      console.log('🚀 ~ onExpand: ~ record:', record);
      expendStatus.value = false;
      if (expanded) {
        detailInfo.value = {
          id: record.id,
          freightTypeId: data.freightTypeId,
          contractId: data.contractId,
          carrierMid: data.mid2,
          ownerMid: data.mid,
          originCode: record.originCode,
          destCode: record.destCode,
        };
      }
    },

    api: getFreightInfoListAPI,
    beforeFetch: (params) => {
      return {
        ...params,
        freightTypeId: data.freightTypeId,
        contractId: data.contractId,
        carrierMid: data.mid2,
        ownerMid: data.mid,
        // ownerMid: 85,
      };
    },
    afterFetch: (res) => {
      return res.map((item) => {
        id.value += 1;
        return {
          ...item,
          id: id.value,
          origin: item.originProvince + item.originCity + (item.originCounty || ''),
          dest: item.destProvince + item.destCity + (item.destCounty || ''),
        };
      });
    },
  });

  const handleAttachmentChange = (data: any) => {
    const { upload, success } = data[0];
    message.success(`已上传${upload}条数据，成功上传${success}条数据`);
    reload();
  };

  const download = async () => {
    const data = (await downloadFreightTemplate()) as any;
    console.log('🚀 ~ download ~ data:', data);
    downloadFile(data, '运费信息导入模板.xlsx');
  };

  const [registerDestinationModal, { openModal: openModalDestinationModal }] = useModal();

  // 新增地址
  const addAddress = () => {
    openModalDestinationModal(true, {
      type: 'add',
      freightTypeId: data.freightTypeId,
      freightType: data.freightType,
      contractId: data.contractId,
      carrierMid: data.mid2,
      ownerMid: data.mid,
    });
  };

  function createActions(record: EditRecordRow): ActionItem[] {
    return [
      // {
      //   label: '编辑',
      //   onClick: handleEdit.bind(null, record),
      // },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
        },
      },
    ];
  }

  // function handleEdit(record: Recordable) {
  //   openModalDestinationModal(true, {
  //     type: 'edit',
  //     freightTypeId: data.freightTypeId,
  //     freightType: data.freightType,
  //     contractId: data.contractId,
  //     carrierMid: data.mid2,
  //     ownerMid: data.mid,
  //     originArea: [record.originProvince, record.originCity, record.originCounty],
  //     originCode: record.originCode,
  //     originCity: record.originCity,
  //     originCounty: record.originCounty,
  //     originProvince: record.originProvince,
  //     destArea: [record.destProvince, record.destCity, record.destCounty],
  //     destCode: record.destCode,
  //     destCity: record.destCity,
  //     destCounty: record.destCounty,
  //     destProvince: record.destProvince,
  //   });
  // }

  async function handleDelete(record: Recordable) {
    try {
      await deleteByCode({
        contractId: data.contractId,
        carrierMid: data.mid2,
        ownerMid: data.mid,
        freightTypeId: data.freightTypeId,
        originCode: record.originCode,
        destCode: record.destCode,
      });
      message.success('删除成功');
      reload();
    } catch (error) {
      console.log('🚀 ~ handleDelete ~ error:', error);
    }
  }

  defineExpose({
    reload,
  });
</script>

<style scoped></style>
